#include "snake.h"
#include <QDebug>

Snake::Snake(int gameWidth, int gameHeight, int stepSize, QObject *parent) :
    QObject(parent),
    m_gameWidth(gameWidth),
    m_gameHeight(gameHeight),
    m_stepSize(stepSize)
{
    reset(); // 初始化蛇
}

void Snake::setDirection(Direction dir)
{
    // 防止180度转向
    if ((m_dir == Up && dir == Down) || 
        (m_dir == Down && dir == Up) || 
        (m_dir == Left && dir == Right) || 
        (m_dir == Right && dir == Left)) {
        return; // 忽略反向操作
    }
    m_dir = dir;
}

void Snake::move()
{
    m_lastDir = m_dir;
    // 记录当前头位置（将成为身体的一部分）
    QPoint prevHead = m_head;
    
    // 根据方向移动蛇头
    switch (m_dir) {
    case Up:
        m_head.setY(m_head.y() - m_stepSize);
        break;
    case Down:
        m_head.setY(m_head.y() + m_stepSize);
        break;
    case Left:
        m_head.setX(m_head.x() - m_stepSize);
        break;
    case Right:
        m_head.setX(m_head.x() + m_stepSize);
        break;
    }
    
    // 边界检测（穿墙效果）
    if (m_head.x() < 0) m_head.setX(m_gameWidth - m_stepSize);
    if (m_head.x() >= m_gameWidth) m_head.setX(0);
    if (m_head.y() < 0) m_head.setY(m_gameHeight - m_stepSize);
    if (m_head.y() >= m_gameHeight) m_head.setY(0);
    
    // 将之前的头添加到身体
    m_body.prepend(prevHead);
    
    // 如果不需要增长，则移除尾部
    if (!m_needToGrow) {
        m_body.removeLast();
    } else {
        m_needToGrow = false;
    }
}

void Snake::grow()
{
    m_needToGrow = true;
}

bool Snake::checkSelfCollision() const
{
    // 检查蛇头是否与身体碰撞
    return m_body.contains(m_head);
}

void Snake::reset()
{
    // 初始化蛇在屏幕中心
    m_head = QPoint(m_gameWidth / 2, m_gameHeight / 2);
    m_body.clear();
    
    // 添加初始身体段
    m_body.append(QPoint(m_head.x() - m_stepSize, m_head.y()));
    m_body.append(QPoint(m_head.x() - m_stepSize * 2, m_head.y()));
    
    // 初始方向向右
    m_dir = Right;
    m_lastDir = Right;
    m_needToGrow = false;
}
